<?php

/**
 * @package Nina
 * @author John Main <john@thedaddy.org>, Andrew Rose <rose.andrew@gmail.com>
 */
class Nina_Db_Driver_Mysqli implements Nina_Db_Driver
{
	private $reg;
	private $dbcon;
	
	public function init(Nina_Registry $reg) {
		$this->reg = $reg;

		if($reg->exists('username,password,hostname')) {
			if($this->connect()) {
				if($this->reg->exists('database') && !$this->database())
					throw new Nina_Exception_Db('Unable to select database ' . $this->reg->get('database'));
				else
					return true;
			}
			else
				throw new Nina_Exception_Db('Unable to establise database connection');
		}
		else
			throw new Nina_Exception_Db('Unable to initilize driver. Missing parameters.');
	}

	public function connect() {
		$this->dbcon = new mysqli($this->reg->get('hostname'), $this->reg->get('username'), $this->reg->get('password'));
		return ($this->dbcon->connect_errno == 0);
	}

	public function database() {
		return $this->dbcon->select_db($this->reg->get('database'));
	}
	
	public function prepare($sql) {
		$stmt = new Nina_Db_Driver_Statement_Mysql($this->dbcon);
		$stmt->setSql($sql);
		return $stmt;
	}

	public function begin() {
		return $this->query("BEGIN;");
	}

	public function commit() {
		return $this->query("COMMIT;");
	}

	public function rollback() {
		return $this->query("ROLLBACK;");
	}

	/**
	 * Get the database fields
	 * @param string $table Table name
	 * @return array
	 */
	public function getFields($table) {
		$rs = $this->query('SHOW COLUMNS FROM ' . $table);
		if ($rs->count()) {
			$fields = array();

			while ($row = $rs->row()) {
				$fields[] = $row['Field'];
			}

			return $fields;
		}
		else
			return false;
	}

	/**
	 * Get the database tables
	 * @return array
	 */
	public function getTables() {
		$rs = $this->query('SHOW TABLES');
		if ($rs->count()) {
			$tables = array();

			while ($row = $rs->row()) {
				$tables[] = reset($row);
			}

			return $tables;
		}
		else
			return false;
	}

	public function query($query) {
		$stmt = $this->prepare($query);

		if($result = $stmt->execute())
			return $result;
		else {
			throw new Nina_Exception_Db_Driver($this->dbcon->error());
			die();
		}
	}
	
	public function insertId() {
		return $this->dbcon->insert_id;
	}
	
	public function escape($data) {
		return $this->dbcon->escape_string($data);
	}
	
	public function lastError() {
		return $this->dbcon->error();
	}

	public function close() {
		return $this->dbcon->close();
	}

	public function ping() {
		return $this->dbcon->ping();
	}
}
